package com.yyq;

import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yyq
 * @create 2021-11-08 14:29
 */
public class zzbds {

    /**
     * 得到网页中图片的地址
     */
    public static String getImgStr(String htmlStr) {

        String img = "";
        String src="";
        Pattern p_image;
        Matcher m_image;
        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                src= m.group();
                if(src.length()!=0){
                    src=src.substring(src.indexOf("\"")+1,src.lastIndexOf("\""));
                }
                return src;
            }
        }

        return null;
    }
    //![]()正则表达式
    public static String getLocImgSrc(String str,String path){
        Matcher matcher = Pattern.compile("!\\[.*\\]\\(.*\\)").matcher(str);
        while ((matcher.find())){
            str= matcher.group();
            String substring = str.substring(str.indexOf("(")+1,str.indexOf(")"));
            if(substring.contains("..")){

                String replace = substring.replace('/', '\\');
                System.out.println(replace);
                replace=replace.substring(2,replace.length());
                String subPath = path.substring(0, path.lastIndexOf('\\'));
                String subPathFinal = subPath.substring(0, subPath.lastIndexOf('\\'));
                System.out.println(subPathFinal);
                System.out.println(subPathFinal+replace);

                return subPathFinal+replace;
                //获取前面
                /*String subPath = path.substring(0, path.lastIndexOf("\\"));
                System.out.println(subPath);
                String subPath2 = subPath.substring(0, subPath.indexOf("\\"));
                System.out.println(subPath2);
                String hz = substring.substring(2, substring.length());
                substring=subPath2+hz;*/

            }
            return substring;
        }
        return null;
    }

    public static String dealStr(String str,String path){
        //情况一 提取img中的url
        String imgStr = getImgStr(str);
        if(imgStr!=null) return imgStr;
        //情况二 提取![]中的url
        if(imgStr==null){
            String locImgSrc = getLocImgSrc(str,path);
            if(locImgSrc!=null){
                return locImgSrc;
            }
        }
        return null;
    }

    public static void main(String[] args) {


    }
}
